//
//  MenuItem.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation

// 菜品分类枚举
enum MenuCategory: String, Codable, CaseIterable {
    case recommended = "推荐"
    case promotion = "促销"
    case combo = "套餐"
    case main = "主菜"
    case side = "配菜"
    case chicken = "炸鸡"
    case drinks = "饮品"
    case desserts = "甜品"
    
    var englishName: String {
    switch self {
        case .recommended: return "Must Try"
        case .promotion: return "Promo"
        case .combo: return "Set"
        case .main: return "Main Dishes"
        case .side: return "Side Dishes"
        case .chicken: return "Fried Chicken"
        case .drinks: return "Drinks"
        case .desserts: return "Desserts"
        }
    }
}

// 肉类选择
enum MeatType: String, Codable, CaseIterable {
    case chicken = "鸡肉"
    case beef = "牛肉"
    
    var chineseName: String {
        rawValue
    }

    var englishName: String {
        switch self {
        case .chicken: return "Chicken"
        case .beef: return "Beef"
        }
    }
}

// 辣度选择
enum SpicyLevel: String, Codable, CaseIterable {
    case mild = "不辣"
    case spicy = "辣"
    
    var englishName: String {
        switch self {
        case .mild: return "Non-Spicy"
        case .spicy: return "Spicy"
        }
    }
}

// 饮品类型（酒精/非酒精）
enum DrinkType: String, Codable, CaseIterable {
    case alcoholic = "酒精饮料"
    case nonAlcoholic = "非酒精饮料"
    
    var englishName: String {
        switch self {
        case .alcoholic: return "Alcoholic"
        case .nonAlcoholic: return "Non-Alcoholic"
        }
    }
}

// 价格选项
struct PriceOption: Identifiable, Codable, Hashable {
    let id: UUID
    let quantity: Int
    let description: String
    let englishDescription: String
    let price: Double
    let isDefault: Bool
    
    init(quantity: Int, description: String, englishDescription: String, price: Double, isDefault: Bool = false) {
        self.id = UUID()
        self.quantity = quantity
        self.description = description
        self.englishDescription = englishDescription
        self.price = price
        self.isDefault = isDefault
    }
}

// 菜品模型
struct MenuItem: Identifiable, Codable, Hashable {
    var id: UUID
    let backendId: Int? // 后端数据库ID
    let name: String
    let englishName: String
    let description: String
    let englishDescription: String
    let price: Double
    let category: MenuCategory
    let imageName: String // 保留原有字段用于向后兼容
    let realImageName: String? // 新增：本地真实图片名称
    let imageURL: String? // 新增：网络图片URL
    let isAvailable: Bool
    let ingredients: [String]
    let availableMeatTypes: [MeatType]
    let isSpicy: Bool
    let isVegetarian: Bool
    let drinkType: DrinkType? // 饮品类型（仅饮品类别使用）
    let priceOptions: [PriceOption]? // 多种价格选项
    let availableSpicyLevels: [SpicyLevel]? // 可选辣度
    let ingredientDescription: String? // 语句化配料描述（中文）
    let englishIngredientDescription: String? // 语句化配料描述（英文）
    
    init(name: String, englishName: String, description: String, englishDescription: String, price: Double, category: MenuCategory, imageName: String, realImageName: String? = nil, imageURL: String? = nil, isAvailable: Bool = true, ingredients: [String] = [], availableMeatTypes: [MeatType] = [], isSpicy: Bool = false, isVegetarian: Bool = false, drinkType: DrinkType? = nil, priceOptions: [PriceOption]? = nil, availableSpicyLevels: [SpicyLevel]? = nil, ingredientDescription: String? = nil, englishIngredientDescription: String? = nil, backendId: Int? = nil) {
        self.id = UUID()
        self.backendId = backendId
        self.name = name
        self.englishName = englishName
        self.description = description
        self.englishDescription = englishDescription
        self.price = price
        self.category = category
        self.imageName = imageName
        self.realImageName = realImageName
        self.imageURL = imageURL
        self.isAvailable = isAvailable
        self.ingredients = ingredients
        self.availableMeatTypes = availableMeatTypes
        self.isSpicy = isSpicy
        self.isVegetarian = isVegetarian
        self.drinkType = drinkType
        self.priceOptions = priceOptions
        self.availableSpicyLevels = availableSpicyLevels
        self.ingredientDescription = ingredientDescription
        self.englishIngredientDescription = englishIngredientDescription
    }
    
    // 获取默认价格选项
    var defaultPriceOption: PriceOption? {
        return priceOptions?.first(where: { $0.isDefault }) ?? priceOptions?.first
    }
    
    // 获取显示价格（优先显示默认价格选项）
    var displayPrice: Double {
        return defaultPriceOption?.price ?? price
    }
    
    // 获取最佳图片显示方案
    var bestImageSource: ImageSource {
        // 优先使用网络图片URL
        if let imageURL = imageURL, !imageURL.isEmpty {
            // 处理网络图片URL
            if imageURL.hasPrefix("http") {
                return .remote(imageURL)
            } else {
                // 构建完整的URL
                let fullURL = AppConfig.apiBaseURL + (imageURL.hasPrefix("/") ? "" : "/") + imageURL
                print("构建完整图片URL: \(fullURL)")
                return .remote(fullURL)
            }
        }
        
        // 如果没有网络图片，使用分类默认占位符
        switch category {
        case .drinks:
            return .placeholder("cup.and.saucer")
        case .chicken:
            return .placeholder("fork.knife")
        case .desserts:
            return .placeholder("birthday.cake")
        default:
            return .placeholder("photo")
        }
    }
}

// 图片来源枚举
enum ImageSource {
    case local(String) // 本地图片名称
    case remote(String) // 网络图片URL
    case placeholder(String) // 占位符/系统图标
}

// 购物车项目
struct CartItem: Identifiable, Codable, Equatable {
    var id: UUID
    let menuItem: MenuItem
    var quantity: Int
    var selectedMeatType: MeatType?
    var specialInstructions: String
    var selectedPriceOption: PriceOption? // 选择的价格选项
    var selectedSpicyLevel: SpicyLevel? // 选择的辣度
    
    init(menuItem: MenuItem, quantity: Int, selectedMeatType: MeatType? = nil, specialInstructions: String = "", selectedPriceOption: PriceOption? = nil, selectedSpicyLevel: SpicyLevel? = nil) {
        self.id = UUID()
        self.menuItem = menuItem
        self.quantity = quantity
        self.selectedMeatType = selectedMeatType
        self.specialInstructions = specialInstructions
        self.selectedPriceOption = selectedPriceOption
        self.selectedSpicyLevel = selectedSpicyLevel
    }
    
    var totalPrice: Double {
        let itemPrice = selectedPriceOption?.price ?? menuItem.price
        return itemPrice * Double(quantity)
    }
    
    // Equatable协议实现
    static func == (lhs: CartItem, rhs: CartItem) -> Bool {
        return lhs.id == rhs.id &&
               lhs.menuItem.id == rhs.menuItem.id &&
               lhs.quantity == rhs.quantity &&
               lhs.selectedMeatType == rhs.selectedMeatType &&
               lhs.specialInstructions == rhs.specialInstructions &&
               lhs.selectedPriceOption == rhs.selectedPriceOption &&
               lhs.selectedSpicyLevel == rhs.selectedSpicyLevel
    }
}